﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Globalization;

namespace AmorCanino.Common
{
    public static class CriptoSecurity
    {
        private const long SALT_VALUE_SIZE = 256;

        public static string HashPassword(string clearData)
        {
            clearData.ThrowIfNull();

            var encoding = new UnicodeEncoding();
            var hash = SHA256.Create();
            var saltValue = ConfigurationHandler.GetHashSalt;

            saltValue.ThrowIfNull();

            byte[] binarySaltValue = new byte[SALT_VALUE_SIZE];
            binarySaltValue[0] = byte.Parse(saltValue.Substring(0, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat);
            binarySaltValue[1] = byte.Parse(saltValue.Substring(2, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat);
            binarySaltValue[2] = byte.Parse(saltValue.Substring(4, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat);
            binarySaltValue[3] = byte.Parse(saltValue.Substring(6, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat);

            byte[] valueToHash = new byte[SALT_VALUE_SIZE + encoding.GetByteCount(clearData)];
            byte[] binaryPassword = encoding.GetBytes(clearData);

            binarySaltValue.CopyTo(valueToHash, 0);
            binaryPassword.CopyTo(valueToHash, SALT_VALUE_SIZE);

            byte[] hashValue = hash.ComputeHash(valueToHash);

            string hashedPassword = string.Empty;

            foreach (byte hexdigit in hashValue)
            {
                hashedPassword += hexdigit.ToString("X2", CultureInfo.InvariantCulture.NumberFormat);
            }

            return hashedPassword;
        }
    }
}
